from flask import Flask
from flask_cors import CORS
from api.back_trade import back_trade
from api.stock_codes import stock_codes
from api.stock_info import stock_info
from api.stock_group import stock_group
from api.optimization import optimization  # 导入优化API蓝图
from api.strategy_combination import strategy_combination  # 导入策略组合API蓝图
from api.real_stock_data import real_stock_data  # 导入实盘数据API蓝图
from api.trading_days import trading_days  # 导入交易日API蓝图
import threading
import schedule
import time
import requests
import logging
from datetime import datetime
import os

app = Flask(__name__)
# 配置CORS，允许跨域请求
CORS(app, resources={r"/*": {"origins": "*"}})

# 获取当前文件所在目录的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
logs_dir = os.path.join(current_dir, 'logs')

# 确保日志目录存在
os.makedirs(logs_dir, exist_ok=True)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(os.path.join(logs_dir, 'scheduler.log'), encoding='utf-8'),
        logging.StreamHandler()
    ]
)

def pull_all_real_stock_data():
    """
    执行拉取所有实盘股票数据的任务
    """
    try:
        logging.info("开始执行定时任务: 拉取所有实盘股票数据")
        
        # 调用API
        response = requests.post('http://localhost:5001/pullAllRealStockData', timeout=3600)  # 1小时超时
        
        if response.status_code == 200:
            result = response.json()
            logging.info(f"定时任务执行成功: {result.get('message', '未知')}")
        else:
            logging.error(f"定时任务执行失败: HTTP {response.status_code} - {response.text}")
            
    except requests.exceptions.Timeout:
        logging.error("定时任务执行超时")
    except requests.exceptions.ConnectionError:
        logging.error("无法连接到API服务器")
    except Exception as e:
        logging.error(f"定时任务执行异常: {str(e)}")

def run_scheduler():
    """
    在后台线程中运行定时任务调度器
    """
    # 每天15:30执行
    schedule.every().day.at("15:30").do(pull_all_real_stock_data)
    
    logging.info("定时任务已设置: 每天15:30执行拉取实盘股票数据")
    
    # 打印下次执行时间
    next_run = schedule.next_run()
    if next_run:
        logging.info(f"下次执行时间: {next_run.strftime('%Y-%m-%d %H:%M:%S')}")
    
    while True:
        try:
            schedule.run_pending()
            time.sleep(60)  # 每分钟检查一次
            
            # 每小时打印一次状态
            if datetime.now().minute == 0:
                logging.info("定时任务调度器运行中...")
                
        except Exception as e:
            logging.error(f"定时任务调度器异常: {str(e)}")
            time.sleep(60)  # 异常后等待1分钟再继续

def start_scheduler():
    """
    启动定时任务调度器（在后台线程中运行）
    """
    scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
    scheduler_thread.start()
    logging.info("定时任务调度器已在后台启动")

# 注册蓝图
app.register_blueprint(back_trade)
app.register_blueprint(stock_codes)
app.register_blueprint(stock_info)
app.register_blueprint(stock_group)
app.register_blueprint(optimization)  # 注册优化API蓝图
app.register_blueprint(strategy_combination)  # 注册策略组合API蓝图
app.register_blueprint(real_stock_data)  # 注册实盘数据API蓝图
app.register_blueprint(trading_days)  # 注册交易日API蓝图

if __name__ == '__main__':
    # 启动定时任务调度器
    start_scheduler()
    
    # 启动Flask应用
    app.run(host='0.0.0.0', port=5001, debug=True)